﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using JBeamLibrary;
using JBeamLibrary.Tools;
using JBeamLibrary.Types;
using NativeLibrary;

namespace DriveBeamEditor.Forms
{
    public partial class OpenVehicleForm : Form, IMessageFilter
    {
        #region Properties

        /// <summary>Gets the selected vehicle name</summary>
        public string SelectedVehicleName
        {
            get
            {
                return lbVehicles.SelectedIndex >= 0 ? ((TaggedString)lbVehicles.SelectedItem).Tag.ToStringOrEmpty() : null;
            }
        }

        #endregion

        #region CTORs

        public OpenVehicleForm()
        {
            Application.AddMessageFilter(this);
            InitializeComponent();
        }

        #endregion

        #region Events

        private void OpenVehicleForm_Load(object sender, EventArgs e)
        {
            if (DesignMode) return;

            RefreshVehicles();
        }

        private void btOpen_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.OK;
            if (!Modal) Close();
        }

        private void btCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            if (!Modal) Close();
        }

        private void btRefresh_Click(object sender, EventArgs e)
        {
            RefreshVehicles();
        }

        #endregion

        #region Methods

        /// <summary>Reloads the valid vehicles into the vehicles list</summary>
        public void RefreshVehicles()
        {
            /* Add valid vehicles to the list */
            lbVehicles.Items.Clear();
            lbVehicles.Items.AddRange(Vehicle.GetValidVehicles().Cast<object>().ToArray());
        }

        #endregion

        #region IMessageFilter

        public bool PreFilterMessage(ref Message m)
        {
            switch (m.Msg)
            {
                case (int)WindowsMessages.WM_KEYDOWN:
                    var key = (Keys)(int)m.WParam & Keys.KeyCode;
                    switch (key)
                    {
                        case Keys.Enter:
                            btOpen.PerformClick();
                            return true;
                        case Keys.Escape:
                            btCancel.PerformClick();
                            return true;
                        case Keys.F5:
                            btRefresh.PerformClick();
                            return true;
                    }
                    break;
            }
            return false;
        }

        #endregion
    }
}
